﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PinCity.Models.Accounts;
using NHibernate.Criterion;
using PinCity.Localization;
using NHibernate;
using PinCity.ORM;

namespace PinCity.Models.Repositories
{
    public class RolesRepository : Repository<Role>
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(RolesRepository));

        /// <summary>
        /// Returns a role, given its name.
        /// </summary>
        /// <param name="roleName">Name of desired role.</param>
        /// <returns>First role, that matches the criteria, or null.</returns>
        public Role GetRoleByName(string roleName)
        { 
            Role result = null;
            IList<Role> tmp = this.GetAll(Expression.Eq("Name", roleName));
            if (tmp != null)
            {
                result = tmp.FirstOrDefault<Role>();
            }
            return result;
        }

        /// <summary>
        /// Init role repository. Fills
        /// repository with set of predefined roles.
        /// </summary>
        public override void Initialize()
        {
            logger.Info("Init of role repository invoked.");
            Role adminRole = new Role("Admin", LocalizationManager.GetString("adminRoleLocalizedName"), LocalizationManager.GetString("adminRoleDescription"));
            Role userRole = new Role("User", LocalizationManager.GetString("userRoleLocalizedName"), LocalizationManager.GetString("userRoleDescription"));
            Role bannedRole = new Role("Banned", LocalizationManager.GetString("bannedRoleLocalizedName"), LocalizationManager.GetString("bannedRoleDescription"));

            using (ISession session = FluentManager.OpenNewSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(adminRole);
                    session.SaveOrUpdate(userRole);
                    session.SaveOrUpdate(bannedRole);
                    transaction.Commit();
                }
            }

        }
    }
}